package com.xhwl.centiotdata.mq.producer;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2022/01/12/ 10:43
 */
@Slf4j
@Component
public class GeneralProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    private List<String> notLogTopics = new ArrayList<String>(){{
        add(AlarmConstant.IVS1800_INTELLIGENCE_TOPIC);
        add(AlarmConstant.IVS3800_INTELLIGENCE_TOPIC);
    }};

    public void send(String topic, Object data) {
        String dataStr = JSONObject.toJSONString(data);
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, JSONObject.toJSONString(data));
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onSuccess(SendResult<String, Object> result) {
                if (!notLogTopics.contains(topic)) {
                    log.info("MQ send successfully！ topic : {} data : {}", topic, dataStr);
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                log.error("MQ failed to send！ topic : {} data : {}", topic, dataStr);
            }
        });
    }

}
